package app.fitness.fragment;

import java.util.Timer;
import java.util.TimerTask;

import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.razerzone.android.fitness.ActivityFitness;
import com.razerzone.android.fitness.R;

import define.Class;
import define.Constants;

public class SplashScreenFragment extends Fragment {
	/**
	 * View section
	 */
	private Fragment mFm = null;

	/**
	 * Shared Preference section
	 */
	private SharedPreferences mSp;
	public static SharedPreferences.Editor mSpEditor;

	/**
	 * Timer section
	 */
	private Timer mTimer;
	private TimerTask mTt = new TimerTask() {

		@Override
		public void run() {
			/**
			 * Detect Nabu Utility App already installed or not
			 */
			if (Constants.utils.isAppInstalled(Constants.PACKAGE_NAME)) {
				/**
				 * TODO Check the user already signed in or not, If not, always
				 * go to Personal Data Fragment page
				 */

				/**
				 * Show the Using Guide only one time, if is the first time run
				 * App, show Using Guide. In the next time and later, not show
				 * Using Guide anymore
				 */
				if (!mSp.getAll().isEmpty()) {
					mFm = new DashBoardFragment();
					ActivityFitness.mFm.beginTransaction()
							.replace(R.id.fr_content_activity_fitness, mFm)
							// .addToBackStack(null)
							.commitAllowingStateLoss();
				} else {
					mFm = new PersonalDataFragment();
					getFragmentManager()
							.beginTransaction()
							.replace(R.id.fr_content_activity_fitness, mFm,
									Class.PERSONAL_DATA)
							// .addToBackStack(null)
							.commitAllowingStateLoss();
				}
			} else {
				mFm = new DownloadNabuUtilityFragment();
				getFragmentManager().beginTransaction()
						.replace(R.id.fr_content_activity_fitness, mFm)
						// .addToBackStack(null)
						.commitAllowingStateLoss();
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mSp = getActivity().getSharedPreferences(
				Constants.PREFERENCES_WELCOME_NABU, 0);
		mSpEditor = mSp.edit();

		/**
		 * Set Orientation for page
		 */
		getActivity().setRequestedOrientation(
				ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Inflate the layout for this fragment
		View v = inflater.inflate(R.layout.fragment_splashscreen, container,
				false);

		// After some seconds, automatically transfer to Welcome fragment
		mTimer = new Timer();
		try {
			mTimer.schedule(mTt, 5000);
		} catch (Exception e) {
		}

		return v;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// Cancel timer
		if (mTt != null) {
			mTt = null;
		}
		if (mTimer != null) {
			mTimer = null;
		}
	}
}
